
def parse_attribute(attrib_str):
    '''
    将多行的属性字符串解析为嵌套的列表。
    '''
    # 多行字符串分解为单行字符串的列表
    # 并删除字符串中的空白字符和换行符
    lines = attrib_str.split('\n')
    new_lines = []

    for line in lines:
        line = line.strip()

        if len(line) == 0:
            continue
        
        if line.find('=') > -1:
            #print(line)
            pos = line.find('=')
            
            former = line[:pos]
            former = former.replace(' ', '')
            former = former.replace('\t', '')
            
            later = line[pos + 1 :]
            later = later.strip()

            line = former + '=' + later
            #print('>>>', line)

        new_lines.append(line)

    lines = new_lines
    new_lines = []

    # 合并同一属性值的多行字符串
    for n in range(len(lines)):
        if len(lines[n].split('=')) < 2 and lines[n]!='END':
            if len(new_lines):
                new_lines[-1] += lines[n]
        else:
            new_lines.append(lines[n])

    lines = new_lines
    new_lines = []


    def parse_group(lines):
        has_approch = False
        found_keyword = False
        container =[]    
        line_count = 0

        while line_count < len(lines):
            line = lines[line_count]

            if not found_keyword:
                if line.find('GROUP=') > -1 or line.find('OBJECT=') > -1:
                    key = line
                    value = []
                    attrib_type = "__NULL__"
                    attrib_class = "__NULL__"

                    if line_count + 1 < len(lines):
                        if lines[line_count+1].find("GROUPTYPE=") > -1:
                            attrib_type = lines[line_count+1]
                            line_count += 1
                        if lines[line_count+1].find('CLASS=') > -1:
                            attrib_class = lines[line_count+1]
                            line_count += 1

                    found_keyword = True
                    has_approch = True
                else:
                    pass
            else:
                if line == 'END_' + key:
                    sub_approch, sub_container = parse_group(value)

                    if sub_approch:
                        container.append([key, sub_container, attrib_type, attrib_class])
                    else:
                        container.append([key, value, attrib_type, attrib_class])

                    found_keyword = False
                else:
                    value.append(line)

            line_count += 1

        return has_approch, container

    return parse_group(lines)


def format_group(group, tab_str='  '):
    '''
    将嵌套列表形式的属性格式化为多行字符串。
    '''
    def _format_group(group, tab_str, tab_num=0):

        def add_blanks(s, length):
            '''
            将 XXX=YYY
            转换为 XXX     = YYY
            '='前的部分长度为length
            '''
            pos = s.find('=')
            former = s[:pos]            
            later  = s[pos + 1 :]
            return former + ' ' * (length - len(former)) + '= ' + later
        # end def
        
        lines = []

        for item in group:
            if item[0].find("GROUP") > -1 or item[0].find("OBJECT") > -1:
                s =  add_blanks(item[0], 23)
                lines.append('\n' + tab_str * tab_num + s)

                if item[2] != '__NULL__':
                    s = add_blanks(tab_str + item[2], 23)
                    lines.append(tab_str * tab_num + s)

                if item[3] != '__NULL__':
                    s = add_blanks(tab_str + item[3], 23)
                    lines.append(tab_str * tab_num + s)

                lines += _format_group(item[1], tab_str, tab_num+1)
                
                s = add_blanks('END_' + item[0], 23)
                #lines.append(tab_str * tab_num + s)

                if item[0].find("GROUP") > -1:
                    lines.append('\n' + tab_str * tab_num + s)
                else:
                    lines.append(tab_str * tab_num + s)
            else:
                s = add_blanks(item, 21)
                #print(':::', s)
                lines.append(tab_str * tab_num + s)

        return lines
    # end def _format_group()

    lines = _format_group(group, tab_str, tab_num=0)
    lines.append("END")
    return lines



if __name__ == '__main__':
    import LST_hdf4_parser as hp

    filename1 = r'G:\2000LST\2000LST\MOD11A2.A2000049.h26v05.006.2015058135500.hdf'
    filename2 = r'G:\2000LST\2000LST\MOD11A2.A2000057.h26v05.006.2015057173523.hdf'

    #'''
    da1, ds1, dd1 = hp.read_lst_hdf4(filename1)
    #'''

    key0 = 'HDFEOSVersion'
    key1 = 'CoreMetadata.0'
    key2 = 'ArchiveMetadata.0'

    # 只处理value为多行的情况
    cm1 = da1.get(key1)
    cm2 = da1.get(key2)

    has_approch, root_group = parse_attribute(cm1)

    #print(root_group)
    #print('*'*60)

    lines = format_group(root_group, '  ')

    for line in lines:
        print(line)
        pass
    #print(lines)